package com.lvt.example.thinking.in.spring.injection;

import com.lvt.example.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.Map;
import java.util.Optional;

/**
 * desc：依赖注解处理过程
 *
 * @author LT
 * @date 2022/4/4
 */
@Configuration
public class AnnotationDependencyInjectionResolutionDemo {

    @Autowired
    @Lazy
    private User lazyUser;

    // 依赖查找处理
    @Autowired
    private User user;
    // DependencyDescriptor-》
    // 必须：required=true
    // 实时注入：eager=true
    // 通过类型：User.class
    // 字段名称("user"）
    // 是否首要 （primary=true）

    // 集合类型注入
    @Autowired
    private Map<String,User> users;

    @Autowired
    private Optional<User> userOptional;

    public static void main(String[] args) {

        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class（配置类） -> Spring Bean
        applicationContext.register(AnnotationDependencyInjectionResolutionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        // 加载 XML 资源，解析并且生成 BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);

        // 启动 Spring 应用上下文
        applicationContext.refresh();

        // 依赖查找
        AnnotationDependencyInjectionResolutionDemo demo = applicationContext.getBean(AnnotationDependencyInjectionResolutionDemo.class);

        // 期待输出 superUser Bean
        System.out.println("demo.lazyUser = " + demo.lazyUser);
        System.out.println("demo.user = " + demo.user);
        System.out.println("demo.users = " + demo.users);
        System.out.println("demo.userOptional = " + demo.userOptional);

        // 显示地关闭 Spring 应用上下文
        applicationContext.close();
    }
}
